// pages/goodsShenhe/putongGoods/putongGoods.js
const app = getApp();
const date = new Date()
const years = []
const months = []
const days = []
const hours = []
const minutes = []
const seconds = []
for (let i = 1990; i <= date.getFullYear() + 1; i++) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  months.push(i)
}

for (let i = 1; i <= 31; i++) {
  days.push(i)
}

for (let i = 0; i <= 23; i++) {
  hours.push(i)
}
for (let i = 0; i <= 59; i++) {
  minutes.push(i)
  seconds.push(i)
}

Page({
  data: {
    extIndex: 1,
    nowpage: 1,
    totalpage: 1,
    goodsList: [],


    years: years, //日期初始化
    year: '',
    year1: '',
    months: months,
    month: '',
    month1: '',
    days: days,
    day: '',
    day1: '',
    hours: hours,
    hour: '',
    hour1: '',
    minutes: minutes,
    minute: '',
    minute1: '',
    seconds: seconds,
    second: '',
    second1: '',
    valueRiqi: '',
    valueShijian: '',
    showAnceng: false, //暗层
    goodsModalone: false, //商品开始时间年月日弹窗
    goodsModaltwo: false, //商品开始时间时分秒弹窗
    zanshistartTime: '', //点击下一步时暂时年月日时间
    goodsstartTimes: '', //选择后的开始时间订单日期
    startTimestr: '', //开始时间订单日期字符串
    goodssendTimes: '', //选择后的结束时间订单日期
    endTimestr: '', //结束时间订单日期字符串
    startorend: true, //ture是开始时间，flase结束时间

    manprice: '',
    jianprice: '',
    showModal: false, //add弹窗
    inputVal: '',
    date: '',
    time: '',
    totalCount: '', //总共的评价记录数
    huodongList: '',
    actId: '', //活动的ID
    actstar: '',
    actend: '',
    showflag: false
  },
  // m满
  manmanprice(e) {
    this.setData({
      manprice: e.detail.value
    })
  },
  manmanShijiao(e) {
    let that = this
    let values = e.detail.value
    if (values.indexOf('.') != -1) {
      values = (values * 1).toFixed(2)
    }
    if (values == 'NaN') {
      wx.showToast({
        title: '请输入正确的金额',
        icon: 'none'
      })
      values = ''
    }
    that.setData({
      manprice: values
    })
  },
  // mjian
  jianjianprice(e) {
    this.setData({
      jianprice: e.detail.value
    })
  },
  jianjianShijiao(e) {
    let that = this
    let values = e.detail.value;
    let manprice = that.data.manprice
    if (values.indexOf('.') != -1) {
      values = (values * 1).toFixed(2)
    }
    if (values == 'NaN' || (Number(values)> Number(manprice))) {
      wx.showToast({
        title: '请输入正确的满减范围！',
        icon: 'none'
      })
      values = ''
    }
    // if(values > manprice){
    //   console.log(values)
    //   console.log(manprice)
    //   wx.showToast({
    //     title: '请输入正确的满减范围！',
    //     icon: 'none'
    //   })
    //   values = ''
    // }
    that.setData({
      jianprice: values
    })
  },
  getgoodsList() {
    let that = this
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "getGoodsListData",
        nowPage: that.data.nowpage,
        shopId: wx.getStorageSync('shopId'),
        type: 1,
        state: that.data.extIndex,
        goodsTypeId: ''
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        if (res.data.result == 1) {
          setTimeout(function() {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
        } else {
          if (that.data.nowpage == 1) {
            that.setData({
              goodsList: res.data.goodsList,
              totalpage: res.data.totalPage,
              showflag: true
            })
          } else {
            var list = that.data.goodsList;
            for (var i in res.data.goodsList) {
              list.push(res.data.goodsList[i])
            }
            that.setData({
              goodsList: list,
              totalpage: res.data.totalPage,
              showflag: true
            })
          }
          setTimeout(function() {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
        }
      }
    });
  },
  close_dingdanTime() {
    let that = this
    that.setData({
      showAnceng: false, //暗层
      goodsModalone: false, //商品开始时间年月日弹窗
      goodsModaltwo: false, //商品开始时间时分秒弹窗
    })
  },
  // 日期切换
  riqiChange: function(e) {
    let that = this
    const val = e.detail.value
    if (that.data.startorend) {
      this.setData({
        year: this.data.years[val[0]],
        month: this.data.months[val[1]],
        day: this.data.days[val[2]]
      })
    } else {
      this.setData({
        year1: this.data.years[val[0]],
        month1: this.data.months[val[1]],
        day1: this.data.days[val[2]]
      })
    }
  },
  // 时间切换
  shijianChange: function(e) {
    const val = e.detail.value
    let that = this
    if (that.data.startorend) {
      this.setData({
        hour: this.data.hours[val[0]],
        minute: this.data.minutes[val[1]],
        // second: this.data.seconds[val[2]]
      })
    } else {
      this.setData({
        hour1: this.data.hours[val[0]],
        minute1: this.data.minutes[val[1]],
        // second1: this.data.seconds[val[2]]
      })
    }
  },
  // 统计开始时间
  tongJiStart(e) {
    let that = this
    let dates = new Date()
    that.setData({
      year: dates.getFullYear(),
      year1: dates.getFullYear(),
      month: dates.getMonth() + 1,
      month1: dates.getMonth() + 1,
      day: dates.getDate(),
      day1: dates.getDate(),
      hour: dates.getHours(),
      hour1: dates.getHours(),
      minute: dates.getMinutes(),
      minute1: dates.getMinutes(),
      second: '00',
      second1: '00',
      valueRiqi: [dates.getFullYear() - 1990, dates.getMonth(), dates.getDate() - 1],
      valueShijian: [dates.getHours(), dates.getMinutes(), '00'],
    })
    let startorend
    let valueRiqi, valueShijian
    if (e.currentTarget.dataset.startorend == 1) {
      startorend = true
      valueRiqi = [(that.data.year - 1990), that.data.month - 1, that.data.day - 1]
      valueShijian = [that.data.hour, that.data.minute, that.data.second]
    } else {
      startorend = false
      valueRiqi = [(that.data.year1 - 1990), that.data.month1 - 1, that.data.day1 - 1]
      valueShijian = [that.data.hour1, that.data.minute1, that.data.second1]
    }
    this.setData({
      goodsModalone: true,
      showAnceng: true,
      startorend: startorend,
      valueRiqi: valueRiqi,
      valueShijian: valueShijian,
      // year: e.currentTarget.dataset.year * 1,
      // month: e.currentTarget.dataset.month * 1,
    })
  },
  // 统计下一步时间
  xiayiBu: function() {
    let that = this
    let times = {}
    if (that.data.startorend) {
      times.year = that.data.year
      if (that.data.month * 1 < 10) {
        times.month = '0' + that.data.month
      } else {
        times.month = that.data.month
      }
      if (that.data.day * 1 < 10) {
        times.day = '0' + that.data.day
      } else {
        times.day = that.data.day
      }
    } else {
      times.year = that.data.year1
      if (that.data.month1 * 1 < 10) {
        times.month = '0' + that.data.month1
      } else {
        times.month = that.data.month1
      }
      if (that.data.day1 * 1 < 10) {
        times.day = '0' + that.data.day1
      } else {
        times.day = that.data.day1
      }
    }
    this.setData({
      goodsModalone: false,
      goodsModaltwo: true,
      zanshistartTime: times
    })
  },
  // 统计确定时间
  quedingEnd: function() {
    let that = this
    let times = that.data.zanshistartTime
    if (that.data.startorend) {
      if (that.data.hour * 1 < 10) {
        times.hour = '0' + that.data.hour
      } else {
        times.hour = that.data.hour
      }
      if (that.data.minute * 1 < 10) {
        times.minute = '0' + that.data.minute
      } else {
        times.minute = that.data.minute
      }
      // if (that.data.second * 1 < 10) {
      //   times.second = '0' + that.data.second
      // } else {
      //   times.second = that.data.second
      // }
    } else {
      if (that.data.hour1 * 1 < 10) {
        times.hour = '0' + that.data.hour1
      } else {
        times.hour = that.data.hour1
      }
      if (that.data.minute1 * 1 < 10) {
        times.minute = '0' + that.data.minute1
      } else {
        times.minute = that.data.minute1
      }
      // if (that.data.second1 * 1 < 10) {
      //   times.second = '0' + that.data.second1
      // } else {
      //   times.second = that.data.second1
      // }
    }

    let timestr = times.year + '-' + times.month + '-' + times.day + ' ' + times.hour + ':' + times.minute + ':00'
    if (that.data.startorend) {
      this.setData({
        showAnceng: false,
        goodsModaltwo: false,
        goodsstartTimes: times,
        startTimestr: timestr
      })
    } else {
      this.setData({
        showAnceng: false,
        goodsModaltwo: false,
        goodssendTimes: times,
        endTimestr: timestr
      })
    }
  },
  toFabu() {
    if (wx.getStorageSync('shopState') == 1) {
      wx.showToast({
        title: '店铺停用状态下，您无权进行此操作！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    wx.navigateTo({
      url: '/pages/goods/page/goodsFabu/manjianFabu/manjianFabu?actId=' + this.data.actId + '&huodongList=' + JSON.stringify(this.data.huodongList),
    })
  },
  // add弹窗
  setHuodong: function() {
    if (wx.getStorageSync('shopState') == 1) {
      wx.showToast({
        title: '店铺停用状态下，您无权进行此操作！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.setData({
      showModal: true
    })
    // this.bindTimeChange()
  },
  // preventTouchMove: function () {

  // },
  //关闭弹窗
  close_mask: function() {
    this.setData({
      showModal: false
    })
  },
  // 删除活动
  deletehuod() {
    let that = this
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "delAct",
        shopId: wx.getStorageSync('shopId'),
        userId: wx.getStorageSync('userId'),
        actId: that.data.actId
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        setTimeout(function() {
          wx.hideLoading()
        }, 0)
        setTimeout(function() {
          wx.showToast({
            title: res.data.resultNote,
            icon: 'none',
            duration: 1500
          })
        }, 0)
        if (res.data.result == 1) {

        } else {
          that.setData({
            showModal: false
          })
          that.gethuodong()
        }
      }
    });
  },
  // 保存活动
  baocunhuod() {
    let that = this
    if (!that.data.manprice) {
      wx.showToast({
        title: '请输入满足满减的金额',
        icon: 'none'
      })
      return
    }
    if (!that.data.jianprice) {
      wx.showToast({
        title: '请输入满减金额',
        icon: 'none'
      })
      return
    }
    
    if (!that.data.startTimestr) {
      wx.showToast({
        title: '请选择活动开始时间',
        icon: 'none'
      })
      return
    }
    if (!that.data.endTimestr) {
      wx.showToast({
        title: '请选择活动结束时间',
        icon: 'none'
      })
      return
    }
    let wsActBean = {
      actDes: '满' + that.data.manprice + '元减' + that.data.jianprice + '元',
      actFullNum: that.data.manprice,
      actReduceNum: that.data.jianprice,
      actStartTime: that.data.startTimestr,
      actEndTime: that.data.endTimestr,
      actId: that.data.actId
    }
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
      })
    }, 0)
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "addAct",
        shopId: wx.getStorageSync('shopId'),
        userId: wx.getStorageSync('userId'),
        type: 0,
        wsActBean: JSON.stringify(wsActBean)
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        if (res.data.result == 1) {
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
        } else {
          that.setData({
            showModal: false
          })
          that.gethuodong()
        }
      }
    });

  },
  //切换头部
  changIndex(e) {
    let that = this
    that.setData({
      extIndex: e.currentTarget.dataset.index,
      nowpage: 1,
      goodsList: [],
      showflag: false
    })
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0)
    that.getgoodsList()
  },
  // 去商品详情
  toGooodsinfo(e) {
    wx.navigateTo({
      url: '/pages/goods/page/goodsXiangqing/manjianGoods/manjianGoods?goodsid=' + e.currentTarget.dataset.goodsid,
    })
  },
  // 满减活动获取
  gethuodong() {
    let that = this
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "getActList",
        nowPage: that.data.nowpage,
        shopId: wx.getStorageSync('shopId'),
        type: 0
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        console.log(res, '活动')
        if (res.data.result == 1) {
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
        } else {
          let huodong = ''
          let actId = ''
          let actstar = ''
          let actend = ''
          if (res.data.list.length > 0) {
            for (var index1 in res.data.list) {
              if (res.data.list[index1].actState == 0 || res.data.list[index1].actState == 2) {
                huodong = res.data.list[index1]
                actId = res.data.list[index1].actId
                actstar = res.data.list[index1].actStartTime.substring(5, 16)
                actend = res.data.list[index1].actEndTime.substring(5, 16)
              }
            }
            that.setData({
              huodongList: huodong,
              totalCount: res.data.totalCount,
              actId: actId,
              actstar: actstar,
              actend: actend,
              manprice: res.data.list[0].actFullNum,
              jianprice: res.data.list[0].actReduceNum,
              startTimestr: res.data.list[0].actStartTime,
              endTimestr: res.data.list[0].actEndTime,
            })
          } else {
            that.setData({
              huodongList: '',
              actId: '',
              actstar: '',
              actend: '',
              manprice: '',
              jianprice: '',
              startTimestr: '',
              endTimestr: '',
            })
          }
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0)
    that.setData({
      nowpage: 1,
      totalpage: 1,
      goodsList: [],
      showflag: false
    })
    that.getgoodsList()
    that.gethuodong()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let that = this
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0)
    that.setData({
      nowpage: 1,
      totalpage: 1,
      goodsList: [],
      showflag: false
    })
    that.getgoodsList()
    that.gethuodong()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this
    let nowpage = that.data.nowpage
    nowpage = nowpage + 1
    let sumpage = that.data.totalpage
    if (nowpage <= sumpage) {
      setTimeout(function() {
        wx.showLoading({
          title: '加载中',
          mask: true
        })
      }, 0)
      that.setData({
        nowpage: nowpage
      })
      that.getgoodsList()
    } else {
      wx.showToast({
        title: '已经到底了',
        icon: 'none'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '众商联采',
      path: "/pages/login/login", // 路径，传递参数到指定页面。
      // imageUrl:'../../../images/logo/LOGO.png'
      imageUrl: app.globalData.logo
    }
  }
})